"use strict";

const KUtil = require("./KUtil");
const { ErrorLogModel } = require("./../model");

async function generateErrorLog(ctx, error) {
  if (!error) return null;
  const [url, query] = (ctx.originalUrl || "").split("?");
  return {
    url,
    query,
    requestBody: JSON.stringify(ctx.response.body || {}),
    method: ctx.request.method,
    requestIP: KUtil.getRemoteIP(ctx.request),
    responseIP: KUtil.getLocalIP(),
    responseError: "" + error,
  };
}

exports.saveErrLog = async (ctx, error) => {
  const log = await generateErrorLog(ctx, error);
  if (log) await ErrorLogModel.create(log);
};
